package com.browan.constellation;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Handler.Callback;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.ScrollView;
import android.widget.TextView;

import com.browan.constellation.configuration.Configuration;
import com.browan.constellation.configuration.ResourceManager;
import com.browan.constellation.data.HorscropData;
import com.browan.constellation.db.DbHelper;
import com.browan.constellation.util.NetWorkUtil;
import com.browan.constellation.util.Util;
import com.browan.constellation.util.LogUtil.Log;

public class ShowLasterNews extends Activity implements Callback
{

	private final static int PULL_COMPLETE = 0;
	private final static int PULL_ERROR = 1;

	/**
	 * 0 是今天 2是明天 1是本月
	 **/
	public static final String DATE_TIME = "date_time";

	public static final String SELECT_INDEX = "select_index";

	private String url;

	private DbHelper m_dbHelper;

	private String m_DateTime;

	private String m_Title;

	private String m_Des;

	private int m_SelectIndex;

	private ScrollView m_scrollView;

	private ProgressBar m_progressBar;

	private boolean isLoadded = false;

	private PullDataThread m_dataThread;

	private List<HorscropData> list;

	private Handler m_mainHandler = new Handler(this);

	private String TAG = getClass().getSimpleName();

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.last_status);
		m_dbHelper = new DbHelper(this);
		m_scrollView = (ScrollView) findViewById(R.id.scroview);
		m_progressBar = (ProgressBar) findViewById(R.id.progressbar);
		int time = getIntent().getIntExtra(DATE_TIME, -1);
		m_SelectIndex = getIntent().getIntExtra(SELECT_INDEX, -1);
		m_Title = ResourceManager.NAMES[m_SelectIndex - 1] + ResourceManager.DATA_DESC[time];
		setTitle(m_Title);
		url = createUrl(m_SelectIndex, time);
		m_DateTime = getTimdDate(time) + "_" + m_SelectIndex;
		String removeData = Util.getRemoveDate() + "_" + m_SelectIndex;
		m_dbHelper.removeOldLuckData(removeData);

		Log.e(TAG, "url = " + url);
		Log.i(TAG, "dateTime = " + m_DateTime);
		list = fillData(m_DateTime);
		if (null == list)
		{
			if (NetWorkUtil.isLive(this))
			{
				startPull(url);
			}
			else
			{
				showErrorNetWorkDialog("没有发现可用网络！");
			}
		}
		else
		{
			m_progressBar.setVisibility(View.GONE);
			fillView(list);
		}
	}

	private void showErrorNetWorkDialog(String msg)
	{
		AlertDialog.Builder localBuilder = new AlertDialog.Builder(this).setTitle("提示").setMessage(msg);
		localBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				ShowLasterNews.this.finish();
			}
		}).setCancelable(false).create().show();
	}

	private String createUrl(int selectIndex, int type)
	{
		return Configuration.HORS_URL + selectIndex + "&type=" + type + "&lang=zh";
	}

	private String getTimdDate(int type)
	{
		String time = "";
		switch (type)
		{
		case 0:
			time = Util.getToday();
			break;

		case 1:
			time = Util.getMonthDate();
			break;

		case 2:
			time = Util.getTomorrow();
			break;
		}
		return time;
	}

	private List<HorscropData> fillData(String time)
	{
		List<HorscropData> list = null;
		Cursor cursor = m_dbHelper.qureyLuck(time);
		if (cursor.moveToFirst())
		{
			list = new ArrayList<HorscropData>();
			do
			{
				HorscropData data = new HorscropData(cursor);
				list.add(data);
			}
			while (cursor.moveToNext());
		}
		cursor.close();
		return list;
	}

	private void fillView(List<HorscropData> list)
	{
		LinearLayout localLinearLayout = new LinearLayout(this);
		ViewGroup.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);
		localLinearLayout.setLayoutParams(params);
		localLinearLayout.setOrientation(LinearLayout.VERTICAL);
		localLinearLayout.setPadding(20, 0, 20, 10);
		for (HorscropData data : list)
		{
			localLinearLayout.addView(createView(data));
		}
		m_scrollView.addView(localLinearLayout);
	}

	private View createView(HorscropData data)
	{
		View view = LayoutInflater.from(this).inflate(R.layout.rinbar, null);

		TextView tv = (TextView) view.findViewById(R.id.title);
		TextView des = (TextView) view.findViewById(R.id.des);
		RatingBar ratingBar = (RatingBar) view.findViewById(R.id.rbar);
		if (-1 == data.getRate())
		{
			ratingBar.setVisibility(View.GONE);
		}
		else
		{
			ratingBar.setProgress(data.getRate());
		}
		tv.setText(data.getName());
		des.setText(data.getDesc());
		return view;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu)
	{
		menu.clear();
		if (isLoadded)
		{
			menu.add(0, Menu.FIRST, 0, "分享").setIcon(android.R.drawable.ic_menu_share);
		}
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		boolean ret = true;
		switch (item.getItemId())
		{
		case Menu.FIRST:
			Intent intent = new Intent(Intent.ACTION_SEND);
			intent.setType("text/plain");
			intent.putExtra(Intent.EXTRA_SUBJECT, m_Title);
			intent.putExtra(Intent.EXTRA_TEXT, getDes());
			startActivity(Intent.createChooser(intent, getTitle()));
			break;

		default:
			ret = super.onOptionsItemSelected(item);
			break;
		}
		return ret;
	}

	private String getDes()
	{
		StringBuilder builder = new StringBuilder();

		for (HorscropData data : list)
		{
			builder.append(data.getName()).append("\n").append(data.getDesc()).append("\n");
		}
		return builder.toString();
	}

	private void startPull(String url)
	{
		stopPull();
		m_dataThread = new PullDataThread(url);
		m_dataThread.start();
	}

	private void stopPull()
	{
		if (null != m_dataThread)
		{
			m_dataThread.interrupt();
			m_dataThread = null;
		}
	}

	private class PullDataThread extends Thread
	{
		private boolean isUseFul = false;
		private final String pullUrl;

		public PullDataThread(String url)
		{
			this.pullUrl = url;
		}

		@Override
		public void run()
		{
			super.run();
			try
			{
				List<HorscropData> list = parse();
				if (isUseFul)
				{

					for (HorscropData data : list)
					{
						m_dbHelper.insertLuck(data.getName(), data.getDesc(), m_DateTime, data.getRate());
					}
					ShowLasterNews.this.list = list;
					m_mainHandler.sendEmptyMessage(PULL_COMPLETE);
				}
			}
			catch (Exception e)
			{
				m_mainHandler.sendEmptyMessage(PULL_ERROR);
			}
		}

		@Override
		public synchronized void start()
		{
			isUseFul = true;
			super.start();
		}

		@Override
		public void interrupt()
		{
			isUseFul = false;
			super.interrupt();
		}

		private List<HorscropData> parse() throws Exception
		{
			DocumentBuilderFactory localDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
			List<HorscropData> list = new ArrayList<HorscropData>();

			DocumentBuilder localDocumentBuilder1 = localDocumentBuilderFactory.newDocumentBuilder();
			NodeList root = localDocumentBuilder1.parse(new URL(pullUrl).openConnection().getInputStream())
					.getDocumentElement().getElementsByTagName("DATA").item(0).getChildNodes();
			for (int i = 0; i < root.getLength(); i++)
			{
				Node node = root.item(i);
				String name = node.getNodeName();
				if (name.equalsIgnoreCase("DESC"))
				{
					if (!isUseFul)
					{
						return list;
					}
					HorscropData data = new HorscropData();
					data.setDesc(node.getFirstChild().getNodeValue());
					NamedNodeMap namedNodeMap = node.getAttributes();

					for (int j = 0; j < namedNodeMap.getLength(); j++)
					{
						Node n = namedNodeMap.item(j);
						if (n.getNodeName().equalsIgnoreCase("NAME"))
						{
							data.setName(n.getNodeValue());
						}
						else if (n.getNodeName().equalsIgnoreCase("RATE"))
						{
							data.setRate(Integer.parseInt(n.getNodeValue()));
						}
					}
					if (!isUseFul)
					{
						return list;
					}
					list.add(data);
				}
			}
			return list;
		}
	}

	protected void onDestroy()
	{
		stopPull();
		m_dbHelper.close();
		super.onDestroy();
	}

	@Override
	public boolean handleMessage(Message msg)
	{
		switch (msg.what)
		{
		case PULL_COMPLETE:
			isLoadded = true;
			m_progressBar.setVisibility(View.GONE);
			fillView(fillData(m_DateTime));
			break;

		case PULL_ERROR:
			AlertDialog.Builder localBuilder = new AlertDialog.Builder(this).setTitle("提示")
					.setMessage("拉去数据失败，重试还是取消？");
			localBuilder.setPositiveButton("重试", new DialogInterface.OnClickListener()
			{
				@Override
				public void onClick(DialogInterface dialog, int which)
				{
					startPull(url);
				}
			}).setNegativeButton("取消", new DialogInterface.OnClickListener()
			{
				@Override
				public void onClick(DialogInterface dialog, int which)
				{
					ShowLasterNews.this.finish();
				}
			}).setCancelable(false).create().show();
			break;
		default:
			break;
		}

		return false;
	};
}
